<template>
  <view class="mt-file-preview">
    <view v-if="imgArr.length" class="flex flex-wrap">
      <image
        v-for="(item, index) in imgArr"
        :key="index"
        class="w-100rpx h-100rpx mt-10rpx mr-10rpx rd-8rpx"
        :src="item.url"
        @click="previewImage(item.url)"
      ></image>
    </view>
    <view v-if="fileArr.length">
      <view
        v-for="(item, index) in fileArr"
        :key="index"
        class="break-all mt-8rpx text-28rpx text-#007BFF ellipsis decoration-underline"
        @click="previewDocument(item.url)"
        >{{ item.name }}</view
      >
    </view>
  </view>
</template>

<script setup>
import { previewDocument, isImage } from '@/utils/tools';
const prop = defineProps({
  list: {
    type: Array,
    default: () => []
  }
});

const imgArr = ref([]);
const imgPreviewArr = ref([]);
const fileArr = ref([]);

watch(
  () => prop.list,
  (newVal) => {
    if (newVal) {
      imgArr.value = [];
      imgPreviewArr.value = [];
      fileArr.value = [];
      for (const item of newVal) {
        if (isImage(item.url)) {
          imgArr.value.push(item);
          imgPreviewArr.value.push(item.url);
        } else {
          fileArr.value.push(item);
        }
      }
    }
  },
  { immediate: true }
);

function previewImage(url) {
  uni.previewImage({
    current: url,
    urls: imgPreviewArr.value
  });
}
</script>

<style lang="scss" scoped>
.mt-file-preview {
  width: 100%;
}
</style>
